<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
        </el-col>
      </el-row>
      <!-- table -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bdbottom',index1 === 0 ?'bdtop':'','vcenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag type="primary" closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级 三级 -->
              <el-col :span="19">
                <el-row :class="['bdtop',index1 === 0 ?'':'bdtop','vcenter']" v-for="(item2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scpoe">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start" :enterable='false'>
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scpoe.row.id)">编辑</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scpoe.row.id)">删除</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配" placement="top-start">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scpoe.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="roleDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="roleForm" ref="roleFormRef" label-width="70px">
        <el-form-item label="角色">
          <el-input v-model="roleForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="email">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的Dialog -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
      <el-form :model="addForm" ref="addFormRef" label-width="70px">
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限分配 -->
    <el-dialog title="权限分配" :visible.sync="setRightDialogVisible" width="50%" @close="SetRightDialogClosed">
      <el-tree :data="rightsList" :props="treeProps" ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      roleDialogVisible: false,
      addDialogVisible: false,
      setRightDialogVisible: false,
      roleForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      addForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: ''

    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      // console.log(res.data)
      this.roleList = res.data
    },
    // 展示修改框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      console.log(res)
      this.roleForm = res.data
      this.roleDialogVisible = true
    },
    // 关闭修改框
    editDialogClosed () {
      this.$refs.roleFormRef.resetFields()
    },
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 修改角色
    async editRoleInfo () {
      const { data: res } = await this.$http.put(`roles/${this.roleForm.roleId}`, { id: this.roleForm.roleId, roleName: this.roleForm.roleName, roleDesc: this.roleForm.roleDesc })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('成功')
      this.roleDialogVisible = false
      this.getRolesList()
    },
    // 删除role
    async removeRoleById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        console.log(err)
      })
      if (confirmResult !== 'confirm') {
        return this.$message.error('删除用户失败!')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      console.log(res)
      this.$message.success('成功')
      // this.editDialogVisible = false
      this.getRolesList()
    },
    // 添加role
    async addRole () {
      this.addDialogVisible = true
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败')
      }
      // console.log(res)
      this.$message.success('成功')
      this.addDialogVisible = false
      this.getRolesList()
    },
    // 根据id删除对应的权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        console.log(err)
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除!')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      console.log(res)
      this.$message.success('成功')
      // this.getRolesList()
      role.children = res.data
    },
    // 权限分配
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.rightsList = res.data
      // console.log(this.rightsList)
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归形式，获取单个权限数组，放入树形组件
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      })
    },
    SetRightDialogClosed () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.$message.success('成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 0 20px;
}
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
